const http = require('http')
const ConsulConfig = require('./server');
const consul = new ConsulConfig();

// 用http创建一个服务
http.createServer(async (req, res) => {
    const {url, method} = req;
    // 测试健康检查
    if (url === '/health') {
        res.end('OK!');
    }
    // 测试动态读取数据
    if (method === 'GET' && url === '/user/info') {
        try {
            const user = await consul.getConfig('drea').catch((e) => {
                res.end(e);
            });
            res.end(`hello ,my name is  ${user.name} I^m ${user.age}`);
        } catch (e) {
            res.end('err:' + e)
        }

    }
    // 测试数据更新
    if (method === 'GET' && url === '/user') {
        try {
            await consul.setUserConfig('age', 18,(err,res)=>{
                if (err){
                    console.log(err);
                    res.end('ERROR!');
                }else {
                    console.log(res);
                    res.end('OK!');
                }
            })
        } catch (err) {
            console.error(err);
            res.end('ERROR!');
        }
    }
}).listen(4000, '127.0.0.1') // 监听本地的5000 端口

